﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LingShi.DAL;
using LingShi.Helpers;
using System.Data;
using System.Data.SqlClient;

namespace LingShi.Admin
{
    public partial class RoleAddEdit : System.Web.UI.Page
    {
        private int roleId;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                roleId = MyUtils.ParseToInt(Request.QueryString["roleId"], 0);
                RoleInfo role = GetRoleInfo(roleId);
                ShowRoleInfo(role);
            }
        }

        private RoleInfo GetRoleInfo(int roleId)
        {
            RoleInfo role = new RoleInfo();
            using (DBContext db = new DBContext())
            {
                SqlResult result = db.CallProcedure("usp_role_get", roleId);
                if (result.DataSet.Tables.Count > 0 && result.DataSet.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = result.DataSet.Tables[0];
                    role.RoleID = MyUtils.ParseToInt(dt.Rows[0]["role_id"], 0);
                    role.RoleName = MyUtils.ParseToString(dt.Rows[0]["role_type"], "");
                    role.RoleMemo = MyUtils.ParseToString(dt.Rows[0]["role_memo"], "");
                }
            }
            return role;
        }

        private void ShowRoleInfo(RoleInfo role)
        {
            this.txtRoleName.Text = role.RoleName;
            this.txtRoleDescription.Text = role.RoleMemo;
        }

        protected void IbtnSave_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                using (DBContext db = new DBContext())
                {
                    object[] parameters = new object[4];
                    if (roleId == 0) parameters[0] = null;
                    parameters[1] = this.txtRoleName.Text;
                    parameters[2] = this.txtRoleDescription.Text;
                    parameters[3] = "A";
                    SqlResult result = db.CallProcedure("usp_role_add_edit", parameters);

                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

        protected void IbtnCancel_Click(object sender, ImageClickEventArgs e)
        {

        }
    }
}